<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2022-11-21
 * Time: 20:34
 */

namespace App\server\wechat;
use App\server\Cache;
use think\facade\Db;
use support\exception\Forbidden;
use support\exception\ModelError;
use EasyWeChat\Factory;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class OfficialAccount
{
    private $app;
    public $config;
    public function __construct( int $id)
    {
        if(empty($id)){
            throw new Forbidden('传入ID为空');
        }
        $request=request();
        $config=Db::table('wechat_app')->where('id',$id)->find();
        if(!$config){
            throw new ModelError('wechat_app 查询为空');
        }
        $app = Factory::officialAccount($config);
        $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
        $symfony_request->headers = new HeaderBag($request->header());
        $app->rebind('request', $symfony_request);
        $cache=new Cache();
        $app->rebind('cache',$cache);
        $this->app=$app;
        $this->config=$config;
    }

    public  function getApp($id)
    {
        if($this->app){
            return $this->app;
        }
        return (new self($id))->app;
    }

    public static function __callStatic($method, $arguments) {
        if($method==='app'){
            return (new self ($arguments[0]))->app;
        }
    }
}